<?php
namespace app\applet\controller;
use think\Db;
use think\Controller;
use think\Log;
use app\service\apixcxService;
use app\service\billService;
use app\service\xcxService;
use app\service\appletRoomService;
class User extends Controller{

	public function roomlist(){
		$user_id=request()->post("user_id");
		$roomlist=Db::table("roominfo_user")->where("user_id",$user_id)->select();
		if(empty($roomlist)){
			return json(["errCode"=>"1","errormsg"=>"您还没有绑定房屋","roomlist"=>$roomlist]);
		}
		foreach ($roomlist as $key => $value) {
			$roominfo=Db::table("roominfo")->where("id",$value["room_id"])->find();
			$roomlist[$key]["summoney"]=Db::table("bill")->where("out_room_id",$roominfo["out_room_id"])->where("status","WAIT_PAYMENT")->sum("bill_entry_amount");
		}
		return json(["errCode"=>"0","roomlist"=>$roomlist]);
	}

	public function getcommunity(){
		$user_id=request()->post("user_id");
		
		if(strlen($user_id)!="16"){
			return json(["errCode"=>"1"]);
		}
		
		$res=Db::table("applet_community")->where("user_id",$user_id)->find();
		if(!empty($res)){
			return json(["errCode"=>"0","adcode"=>$res["community_id"],"city"=>$res["community_name"]]);
		}else{
			return json(["errCode"=>"1"]);
		}
		
	}
	public function communityupdate(){
		$user_id=request()->post("user_id");
		if(strlen($user_id)!="16"){
			return json(["errCode"=>"1"]);
		}
		$data["community_id"]=request()->post("adcode");
		$data["community_name"]=request()->post("city");
		$res=Db::table("applet_community")->where("user_id",$user_id)->find();
		if(!empty($res)){
			Db::table("applet_community")->where("user_id",$user_id)->update($data);
		}else{
			$data["user_id"]=$user_id;
			Db::table("applet_community")->insert($data);
		}
		return json(["errCode"=>"0"]);
	}
	public function billlistpaid(){
		$user_id=request()->post("user_id");
		//Log::write($user_id,"user_id");
		if(strlen($user_id)!="16"){
			return json(["errCode"=>"1","errormsg"=>"用户信息错误"]);
		}
		$billlist=Db::table("bill")
				->where("user_id",$user_id)
				->where("status",'TRADE_SUCCESS')
				->select();
		if(empty($billlist)){
			return json(["errCode"=>"1","errormsg"=>"未查到账单"]);
		}
		//Log::write($billlist,"123344");
		return json(["errCode"=>"0","billlist"=>$billlist,"errormsg"=>"未查到账单"]);
	}


	public function roominfo(){
        $room_id=request()->post("room_id");
        $roominfo=Db::table("roominfo")
                    ->where("id",$room_id)
                    ->find();
        $communityinfo=Db::table("community")->where("id",$roominfo["community_id"])->find();
        $roominfo["community_name"]=$communityinfo["name"];
        $roominfo["owner_name"]=str_repeat('*', mb_strlen($roominfo['owner_name'])-1).mb_substr($roominfo["owner_name"],-1);
        return json(['errCode'=>'0',"roominfo"=>$roominfo]);
    }
    public function address(){
        $user_id=request()->post("user_id");
        //$user_id="2088112618452297";
        $community_id=request()->post("adcode");
        $service_id=1;
        //查询小区
        
        $str="";
        $str=$str.'[';  
        ///Log::write($community,"community");
        
        //查询组团
        $group=(new appletRoomService())->disgroup($community_id);
        foreach ($group as $gro){
            $str=$str.'{';
            $str=$str.'"name": "'.$gro.'",';
            $str=$str.'"subList": [';
            
            //查询房屋号
            $building=(new appletRoomService())->disbuild($community_id,$gro);
            
            foreach ($building as $build){
                $str=$str.'{';
                    $str=$str.'"name": "'.$build.'",';
                    $str=$str.'"subList": [';
                    //查询单元
                    $unit=(new appletRoomService())->disunit($community_id,$gro,$build);
                    foreach ($unit as $uni){
                        $str=$str.'{';
                            $str=$str.'"name": "'.$uni.'",';
                            $str=$str.'"subList": [';
                            //查询房屋号
                            $room=(new appletRoomService())->disroom($community_id,$gro,$build,$uni);
                            foreach ($room as $roo){
                                $str=$str.'{';
                                    $str=$str.'"name": "'.$roo.'"';
                                $str=$str.'},';
                            }
                            $str=substr($str,0,strlen($str)-1);
                            $str=$str.']';
                        $str=$str.'},';
                    }
                    $str=substr($str,0,strlen($str)-1);
                    $str=$str.']';
                $str=$str.'},';
            }
            $str=substr($str,0,strlen($str)-1);
            
            $str=$str.']';
            $str=$str.'},';
        }
                
        
        $str=substr($str,0,strlen($str)-1);
        $str=$str.']';
        return json_encode($str);
    }
    
    
    public function checkname(){
        $data=request()->post();
        //Log::write($data,"1234");
        $roominfo=Db::table("roominfo")
                    ->where("community_id",$data["community_id"])
                    ->where("zz_group",$data['group'])
                    ->where("building",$data['building'])
                    ->where("unit",$data['unit'])
                    ->where("room",$data['room'])
                    ->find();
        
        $userroom=Db::table("roominfo_user")->where("user_id",$data["user_id"])->where("room_id",$roominfo["id"])->find();
        if(empty($userroom)){
            return json(['errCode'=>'1',"room_id"=>$roominfo["id"]]);
        }else{
            return json(['errCode'=>'0',"room_id"=>$roominfo["id"]]);
        }
    }

    public function checkname_save(){
        $data=request()->post();
        $num=Db::table("roominfo_user")->where("user_id",$data["user_id"])->count();
        if($num>=3){
            return json(['errcode'=>'1','errmsg'=>"最多绑定三户"]); 
        }
        $roominfo=Db::table("roominfo")->where("id",$data["room_id"])->find();
        if($roominfo["owner_name"]==$data["owner_name"]){
            
            $info["user_id"]=$data["user_id"];
            $info["room_id"]=$data["room_id"];
            $info["community_id"]=$roominfo["community_id"];
            
            
            $info["address"]=$roominfo["address"];
            $info["create_time"]=time();
            $communityinfo=Db::table("community")->where("community_id",$roominfo["community_id"])->find();
            $info["community_name"]=$communityinfo["community_name"];
            $res=Db::table("roominfo_user")->insert($info);
            return json(['errcode'=>'0']);
        }else{
            return json(['errcode'=>'1','errmsg'=>"验证失败"]); 
        }
    }
    public function formIdAdd(){
        $applet_form["service_id"]=6;//金城小程序
        $applet_form["ctime"]=time();
        $applet_form["user_id"]=request()->get("user_id");
        $applet_form["form_id"]=request()->get("formId");
        $applet_form["num"]=3;
        $res=Db::table("applet_form")->insert($applet_form);
    }
    public function contract(){
        $user_id=request()->post("user_id");
        if(strlen($user_id)!="16"){
            return json(["errCode"=>"1",'errmsg' => '请绑定房屋']);
        }
        $roomuser=Db::table("roominfo_user")->where("user_id",$user_id)->find();
        if(empty($roomuser)){
            return json(["errCode"=>"1",'errmsg' => '请绑定房屋']);
        }
        $communityinfo=Db::table("community")->where("community_id",$roomuser["community_id"])->find();
        return json(["errCode"=>"0",'phone' => $communityinfo["hotline"]]);
    }
    
    //提交信息计算物业费
    public function details()
    {
        //根据小区和完整门牌号查询房屋信息
        $room_id=request()->post("room_id");
        $roominfo = Db::table("roominfo")->where("id",$room_id)->find();
        //Log::write($roominfo,"122");
        //根据房号查询账单
        $billlis = (new xcxService())->billRoomIdList($roominfo['out_room_id']);
        $billlist = (new xcxService())->cost_type($roominfo['out_room_id']);
         
        foreach ($billlist as $b){
            $lis[] = (new xcxService())->cost_type_bill($roominfo['out_room_id'],$b);
        }
        //$lis = array_unique($lis);
        foreach($billlis as $list){
            $info['acct_period'][] = $list['acct_period'];
            $info['cost_type'][] = $list['cost_type'];
            $info['bill_amount'][] = $list['bill_entry_amount'];
            $info['id'][] = $list['id'];
        }
        if(empty($info)){
            return json(['error' => '暂无可缴费账单']);
        }
        return json_encode($lis);

    }
   
    //确认订单
    public function order(){
        $data=request()->post();
        $user_id =  $data['user_id'];
        $id = $data['id'];

        if(empty($id)){
            return json(['errorCode'=>'1','error' => '请选择要缴费的账单']);
        }
        //根据账单编号查询账单金额
        $infolist = (new billService())->billEntryIdInfo($id);
        if(count($infolist) != count($id)){
            return json(['errorCode'=>'1','info' => '账单信息不完整']);
        }
        $out_room_id="";
        $room_address="";
        $community_id="";
        foreach($infolist as $info){
            //查询小区名称
            $community_name = (new billService())->communityMachine($info['community_id'])['community_name'];
            $bill_entry_amount[] = $info['bill_entry_amount'];
            $out_room_id = $info['out_room_id'];
            $community_id = $info['community_id'];
            $room_address = $info['room_address'];
        }

        $out_trade_no = time().rand(100000,999999);
        $bill_amount_sum = array_sum($bill_entry_amount);
        
        $roominfo=Db::table("roominfo")->where("out_room_id",$out_room_id)->find();
        $subject = $community_name.$room_address.'-'.$roominfo["owner_name"].'物业缴费';
         
        //查询token
        $token = (new xcxService())->token($community_id);
        //Log::write($token,"token");
        $api = new apixcxService();
        $notifyUrl="https://www.jfzhiwen.com/admin/callback/alinotice";
        $result = $api->create(json_encode(['out_trade_no'=> $out_trade_no,'total_amount'=>$bill_amount_sum,'buyer_id'=>$user_id,'subject' =>$subject,'token'=>$token ,'notifyUrl'=>$notifyUrl]));
        
        if(property_exists($result,'sub_msg')){
            return json(['errorCode'=>'1','info' => $result->sub_msg]);
        }else{
            $close_id = $id['0'];
            $is_trade_no = Db::name('bill')->where('id',$close_id)->value('trade_no');
            if(!empty($is_trade_no)){
                
                $aaa = $api->close(json_encode(['trade_no' => $is_trade_no,'token' => $token]));
                if(property_exists($aaa,'sub_msg')){
                   Db::name('test')->insert(['test'=>$aaa->sub_msg]);
                   Db::name('test')->insert(['test'=>$is_trade_no]);
                } 
            }
            //添加进数据库
            $bill['trade_no'] =  $result->trade_no;
            $bill['out_trade_no'] = $out_trade_no;
            $bill['user_id'] = $user_id;
            foreach($id as $billid){
                $bill['id'] = $billid;
                $billedit = (new billService())->billEdit($bill);
                if(empty($billedit)){
                    return json(['errorCode'=>'1','info' => '账单存储失败']);
                }
            }
            $billpay["user_id"]=$user_id;
            $billpay["order_money"]=$bill_amount_sum;
            $billpay["pay_money"]=$bill_amount_sum;
            $billpay["out_trade_no"]= $out_trade_no;
            $billpay["trade_no"]= $bill['trade_no'];
            $billpay["billid"]=serialize($id);
            $billpay["out_room_id"]=$out_room_id;
            $billpay["room_address"]=$room_address;
            $billpay["community_name"]=$community_name;
            $billpay["community_id"]=$community_id;
            $billpay["scenes"]=2;
            $res=Db::table("billpay")->insert($billpay);
            if($res){
                //返回结果到前台唤起收银台
                return json(['trade_no' => $bill['trade_no']]);
            }else{
                return json(['errorCode'=>'1','info' => '账单存储失败']);
            }
            
        }
    }

}